<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/8/31
 * Time: 下午5:08
 */

namespace App\Library\Mall;


use App\Models\Item;
use App\Models\Order;
use Illuminate\Support\Facades\Auth;

class OrderCreator
{
    public $buyer;
    public $seller;
    public $shop;
    public $items = [];
    public $addressId;
    public $payType = 1;
    public $shippingType = 1;
    public $buyerMessage = '';
    public $invoice = [];


    /**
     * @return Order|\Illuminate\Database\Eloquent\Model
     * @throws \Exception
     */
    public function create()
    {

        if (!$this->shop) {
            throw new \Exception('invaild shop value', 1);
        }

        if (empty($this->items)) {
            throw new \Exception('invaild items value', 2);
        }

        if (!$this->addressId) {
            throw new \Exception('invaild addressId value', 3);
        }

        if (!$this->buyer){
            if (Auth::check()) {
                $this->buyer = Auth::user();
            } else {
                throw new \Exception('user unauthorized', 4);
            }
        }

        if (!$this->seller) {
            $this->seller = $this->shop->user;
        }

        $order_no = createOrderNo();
        $trade_no = createTradeNo();

        $order = Order::create([
            'buyer_uid'=>$this->buyer->uid,
            'buyer_name'=>$this->buyer->username,
            'buyer_message'=>$this->buyerMessage,
            'seller_uid'=>$this->seller->uid,
            'seller_name'=>$this->seller->username,
            'shop_id'=>$this->shop->shop_id,
            'shop_name'=>$this->shop->shop_name,
            'order_no'=>$order_no,
            'order_fee'=>0,
            'shipping_fee'=>0,
            'total_fee'=>0,
            'pay_type'=>$this->payType,
            'pay_status'=>0,
            'shipping_type'=>$this->shippingType,
            'shipping_status'=>0,
            'receive_status'=>0,
            'created_at'=>time(),
            'trade_no'=>$trade_no,
            'trade_status'=>1,
        ]);

        $order_fee = 0;
        $shippine_fee = 0;
        $subject = $body = '';
        foreach ($this->items as $item) {
            $simple_fee = $item->price * $item->quantity;
            $order_fee+= $simple_fee;
            $order->items()->create([
                'itemid'=>$item->itemid,
                'title'=>$item->title,
                'price'=>$item->price,
                'thumb'=>$item->thumb,
                'image'=>$item->image,
                'quantity'=>$item->quantity ? $item->quantity : 1,
                'total_fee'=>$simple_fee
            ]);

            if (!$subject) $subject = $item->title;
            if (!$body) $body = $item->title;
        }
        //更新订单价格
        $order->update([
            'order_fee'=>$order_fee,
            'shipping_fee'=>$shippine_fee,
            'total_fee'=>$order_fee+$shippine_fee
        ]);

        //创建配送信息
        $address = $this->buyer->addresses()->find($this->addressId);
        if ($address) {
            $order->shipping()->create([
                'shipping_type'=>$this->shippingType,
                'consignee'=>$address->consignee,
                'phone'=>$address->phone,
                'province'=>$address->province,
                'city'=>$address->city,
                'district'=>$address->distinct,
                'street'=>$address->street,
                'created_at'=>time()
            ]);
        } else {
            $order->shipping()->create([
                'created_at'=>time()
            ]);
        }

        if (is_array($this->invoice) && !empty($this->invoice))
        {
            $order->invoice()->create($this->invoice);
        }

        //添加操作记录
        $order->actions()->create([
            'uid'=>$this->buyer->uid,
            'username'=>$this->buyer->username,
            'content'=>trans('mall.auction success'),
            'created_at'=>time()
        ]);

        //创建交易流水
        if ($this->payType == 1) {
            $order->trade()->create([
                'payer_uid'=>$this->buyer->uid,
                'payer_name'=>$this->buyer->username,
                'payee_uid'=>$this->seller->uid,
                'payee_name'=>$this->seller->username,
                'pay_type'=>'',
                'pay_status'=>0,
                'trade_no'=>$trade_no,
                'subject'=>$subject,
                'body'=>$body,
                'total_amount'=>$order_fee+$shippine_fee,
                'trade_type'=>'shopping',
                'trade_status'=>1,
                'created_at'=>time(),
                'out_trade_no'=>$order_no,
            ]);
        } else {
            $order->changeToPaid();
        }

        //向卖家发送APP通知
        AppMsgClient::sendNewOrderMessage($item->shop->uid);
        //向卖家发送微信订单通知
        try {
            WxMsgClient::sendNewOrderMessage($order, $item->shop);
        } catch (\Exception $e){

        }

        return $order;
    }
}
